package cn.kooki.app.duobao.ui.Activity.Pay;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.iapppay.interfaces.callback.IPayResultCallback;
import com.iapppay.sdk.main.IAppPay;
import com.iapppay.sdk.main.IAppPayOrderUtils;
import com.ipaynow.plugin.api.IpaynowPlugin;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.User.pay.PayResponse;
import cn.kooki.app.duobao.data.Bean.User.pay.PayResult;
import cn.kooki.app.duobao.data.Bean.User.pay.PayTypeRes;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.PayEvent;
import cn.kooki.app.duobao.data.bus.UserRefrshEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.widget.BankPicker;
import cn.kooki.app.duobao.ui.widget.MoneyPicker;
import cn.kooki.app.duobao.util.NetWorkUtils;
import cn.kooki.app.duobao.util.PayUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.SignUtils;
import cn.kooki.app.duobao.util.StringUtils;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/12/13.
 */
public class ReChargeActivity extends BaseNavActivity implements View.OnClickListener {
    @Bind(R.id.moneyTitle)
    TextView moneyTitle;
    @Bind(R.id.moneyPicker)
    MoneyPicker moneyPicker;
    @Bind(R.id.useBankTitle)
    TextView useBankTitle;
    @Bind(R.id.banks)
    BankPicker banks;
    @Bind(R.id.submit)
    Button submit;
    private UserInfo userinfo;

    private PayResponse.PayInfo data;
    private String price;
    // 商户私钥，pkcs8格式

    private int type;
    private IWXAPI api;
    private PayResponse info;

    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_recharge);
        ButterKnife.bind(this);
    }

    @Override
    protected void afterView() {
        setTitle(R.string.title_activity_recharge);
        submit.setOnClickListener(this);
        userinfo = SharePreferencesUtils.getUserinfo(this);
        EventBus.getDefault().post(new UserRefrshEvent());
        getPayType();
    }

    private void getPayType() {
        MainFactory.getApiInstance().getPayType(new Callback<PayTypeRes>() {
            @Override
            public void success(PayTypeRes payTypeRes, Response response) {
                if (payTypeRes.data != null) {
                    fitterType(payTypeRes.data);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                showToastMessage("获取支付方式失败");
                finish();
            }
        });
    }
    private void fitterType(ArrayList<String> data) {
        if (banks != null) {
            int hideType = -1;
            if (!data.contains("聚合")) {
                hideType = BankPicker.WEIXIN_TYPE;
            } else if (!data.contains("爱贝")) {
                hideType = BankPicker.AIBEI_TYPE;
            }
            if (hideType != -1) {
                banks.hideProgress(type);
            } else {
                banks.hideProgress();
            }
        }
    }


    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    public String sign(String content) {
        return SignUtils.sign(content, Constants.RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    public String getSignType() {
        return "sign_type=\"RSA\"";
    }

    @Override
    public void onClick(View v) {
        if (v == submit) {
            if (checkform()) {
                charge();
            }
        }
    }


    private void charge() {
        showLoading("正在加载中...");
        type = 3;
        if (banks.getSelectType() == BankPicker.WEIXIN_TYPE) {
            type = BankPicker.WEIXIN_TYPE;
        } else {
            type = BankPicker.AIBEI_TYPE;
        }
        price = moneyPicker.getselectPrice();
        String ip = NetWorkUtils.getLocalIpAddress();
        MainFactory.getApiInstance().charge(userinfo.getUid(), ip, 4, price, type, new Callback<PayResponse>() {


            @Override
            public void success(PayResponse baseResponse, Response response) {
                dismissLoading();
                if (baseResponse.status == 0) {
                    info = baseResponse;
                    data = baseResponse.data;
                    if (type == BankPicker.WEIXIN_TYPE) {
                        preSign();
                    } else {
                        aibeiPay();
                    }
                } else {
                    showToastMessage("服务器通信错误");
                }
            }

            @Override
            public void failure(RetrofitError error) {
                dismissLoading();
                showToastMessage(getString(R.string.network_error));

            }
        });

    }

    private void aibeiPay() {
        IAppPay.startPay(this, "transid=" + data.transid + "&appid=" + Constants.IPAY_APP_ID, iPayResultCallback);
    }


    private String TAG = "IPAY";
    /**
     * 支付结果回调
     */
    IPayResultCallback iPayResultCallback = new IPayResultCallback() {

        @Override
        public void onPayResult(int resultCode, String signvalue, String resultInfo) {
            // TODO Auto-generated method
            PayEvent event = new PayEvent();
            switch (resultCode) {
                case IAppPay.PAY_SUCCESS:
                    //调用 IAppPayOrderUtils 的验签方法进行支付结果验证
                    boolean payState = IAppPayOrderUtils.checkPayResult(signvalue, PayConfig.publicKey);
                    if (payState) {
                        Toast.makeText(ReChargeActivity.this, "支付成功", Toast.LENGTH_LONG).show();
                        event.isSuccess = true;
                    }
                    break;
                case IAppPay.PAY_ING:
                    Toast.makeText(ReChargeActivity.this, "成功下单", Toast.LENGTH_LONG).show();
                    break;
                default:
                    Toast.makeText(ReChargeActivity.this, resultInfo, Toast.LENGTH_LONG).show();
                    break;
            }
            EventBus.getDefault().post(event);
            Log.d(TAG, "requestCode:" + resultCode + ",signvalue:" + signvalue + ",resultInfo:" + resultInfo);
        }
    };


    public void preSign() {
        String sing = data.sign.replaceAll("\\\\", "");
        IpaynowPlugin.pay(this, sing);
    }


    public void onEventMainThread(PayEvent event) {
        finish();
        if (event.isSuccess) {
            EventBus.getDefault().post(new UserRefrshEvent());
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("type", PayCallBackActivity.CHARGE_TYPE);
            hashMap.put("code", info.dingdan);
            intent2(PayCallBackActivity.class, hashMap);
        }
    }

    private boolean checkform() {
        if (TextUtils.isEmpty(moneyPicker.getselectPrice()) || !StringUtils.isConstentNumber(moneyPicker.getselectPrice())) {
            showToastMessage("请选择充值金额");
            Log.e("price", moneyPicker.getselectPrice());
            return false;
        }
        if (banks.getSelectType() == -1) {
            showToastMessage("请选择充值途径");
            return false;
        }
        return true;

    }
}
